<template>
  <div v-loading="initLoading" class="page-content">
    <div class="text-right">
      <el-button size="small" class="mb-2 d-print-none" v-show="hasNotice" @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
    </div>

    <div v-if="!hasBank" class="p-5 text-center text-muted border rounded bg-light">
      暂无银行认领，请等待银行认领
    </div>

    <div v-else-if="!hasEleReceipt" class="p-5 text-center text-muted border rounded bg-light">
      <span v-if="projectEleStatus === 0">
        <span>尚未发送担保意向函，请先发送担保意向函</span>
      </span>
      <span v-else-if="projectEleStatus === 1">担保意向函未回执，请先等待银行回执</span>
      <span v-else-if="projectEleStatus === 3">担保意向函已被银行拒绝，无法发送放款通知书</span>
    </div>

    <div v-else>
      <div class="pre-style" :id="printId">
        <div>{{ noticeNo }}</div>
        <h3 class="text-center my-3">放款通知书</h3>
        <div>{{ relatedData.bank_name || '' }}：</div>
        <div class="text-indent">
          <span>根据贵行与借款人</span>
          <span class="px-1 text-decoration">
            &nbsp;{{ relatedData.customer_name || '-' }}&nbsp;
          </span>
          <span>（以下简称借款人）于</span>
          <span class="px-1 text-decoration" v-if="isViewModel">
            &nbsp;{{ $utils.dateFormat(contract.contract_date, 'yyyy年MM月dd日') }}&nbsp;
          </span>
          <div v-else class="date-picker-inline d-print-none mx-1">
            <el-date-picker
              v-model="contract.contract_date"
              type="date"
              :placeholder="placeholderTime"
              class="w-100"
              :clearable="false"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
          <span>签订的编号为</span>
          <span class="px-1 text-decoration" v-if="isViewModel">
            &nbsp;{{ contract.credit_contract_no || '' }}&nbsp;
          </span>
          <span v-else class="input-td d-inline-block d-print-none mx-1">
            <input
              type="text"
              class="form-control"
              :placeholder="placeholderNo"
              v-model="contract.credit_contract_no"
            />
          </span>
          <span>
            的{{ enumContractType[contract.contract_type] || '授信合同' }}，贷款金额人民币
          </span>
          <span v-if="isViewModel">
            <span>（大写）</span>
            <span class="px-1 text-decoration">&nbsp;{{ loanFundsChinese }}&nbsp;</span>
          </span>
          <span
            v-else
            class="input-td d-inline-block d-print-none mx-1"
            style="text-indent: 0px; width: 160px"
          >
            <el-input v-model="contract.reply_funds" type="number" placeholder="贷款金额">
              <template slot="append">万元</template>
            </el-input>
          </span>
          <span>，期限为</span>
          <span class="px-1 text-decoration">&nbsp;{{ loanMonths }}&nbsp;</span>
          <span>个月。以及我公司与贵行于</span>
          <span class="px-1 text-decoration" v-if="isViewModel">
            &nbsp;{{ $utils.dateFormat(contract.gua_contract_date, 'yyyy年MM月dd日') }}&nbsp;
          </span>
          <div v-else class="date-picker-inline d-print-none mx-1">
            <el-date-picker
              v-model="contract.gua_contract_date"
              type="date"
              placeholder="保证合同时间"
              class="w-100"
              :clearable="false"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
          <span>签订的编号为</span>
          <span class="px-1 text-decoration" v-if="isViewModel">
            &nbsp;{{ contract.ensure_contract_no || '' }}&nbsp;
          </span>
          <span v-else class="input-td d-inline-block d-print-none mx-1">
            <input
              type="text"
              class="form-control"
              placeholder="保证合同号"
              v-model="contract.ensure_contract_no"
            />
          </span>
          <span>
            的保证合同，现我公司已落实反担保措施，特告知贵行可以为借款人办理发放贷款，金额
          </span>
          <span class="px-1 text-decoration" v-if="isViewModel">
            &nbsp;{{ loanFundsChinese }}&nbsp;
          </span>
          <span
            v-else
            class="input-td d-inline-block d-print-none mx-1"
            style="text-indent: 0px; width: 160px"
          >
            <el-input v-model="contract.reply_funds" type="number" placeholder="贷款金额">
              <template slot="append">万元</template>
            </el-input>
          </span>
          <span>
            ，我公司按照与贵行签订的融资担保合作协议的约定对本通知书项下的贷款承担担保责任。我公司对贵行在本通知书送达贵行之后发放的上述合同项下的贷款承担担保责任。
          </span>
        </div>
        <div class="text-right my-5">{{ contract.accept_entrust_entity_name || '' }}</div>
        <div class="text-right my-5">
          负责人或授权代理人（签字）：{{ contract.entrust_entity_corp }}
        </div>
        <div class="text-right my-5" v-if="isViewModel">{{ noticeDate }}</div>
        <div v-else class="d-print-none input-td text-right">
          <el-date-picker
            v-model="notice.notice_date"
            type="date"
            placeholder="放款通知时间"
            class="w-25"
            :clearable="false"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>

        <div v-if="isBankOrg || +this.relatedData.loan_notice_status > 1">
          <div class="notice-divider"></div>

          <h3 class="text-center my-5">放款通知书回执联</h3>
          <div>通知书编号：{{ noticeNo }}</div>
          <div>借 款 人：{{ relatedData.customer_name || '-' }}</div>
          <div>
            <span>放款金额：</span>
            <span class="px-1 text-decoration">&nbsp;{{ loanFundsChinese }}&nbsp;</span>
            <span>，用款期限</span>
            <span class="px-1 text-decoration">&nbsp;{{ loanMonths }}&nbsp;</span>
            <span>个月</span>
          </div>
          <div>
            <span>出具日期：</span>
            <span>{{ noticeDate }}</span>
          </div>
          <div class="d-flex my-5">
            <div class="flex-1">
              <span>贷款银行（签章）：{{ relatedData.bank_name || '' }}</span>
            </div>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <div class="flex-1">
              <span>经办人（签字）：</span>
              <span v-if="isViewModel || !isBankOrg">{{ notice.bank_agent_name || '' }}</span>
              <span
                v-else
                class="input-td d-inline-block d-print-none mx-1"
                style="text-indent: 0px; width: 160px"
              >
                <el-input v-model="notice.bank_agent_name" placeholder="经办人"></el-input>
              </span>
            </div>
          </div>
          <div class="my-5">
            <span>签收日期：</span>
            <span v-if="isViewModel || !isBankOrg">
              {{ $utils.dateFormat(notice.notice_date_sign, 'yyyy年MM月dd日') || '年 月 日' }}
            </span>
            <div v-else class="date-picker-inline d-print-none mx-1">
              <el-date-picker
                v-model="notice.notice_date_sign"
                type="date"
                placeholder="签收日期"
                :clearable="false"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </div>
          </div>
        </div>
      </div>
      <div class="text-center mt-4" v-if="!isViewModel">
        <el-button @click="submit(0)" type="primary" :loading="submitLoading" class="btn-long">
          {{ isBankOrg ? '提交回执联' : (!hasNotice ? '发送' : '修改') + '放款通知书' }}
        </el-button>
        <el-button
          v-if="isBankOrg"
          @click="submit(1)"
          type="danger"
          :loading="submitLoading"
          class="btn-long"
        >
          拒绝
        </el-button>
      </div>
    </div>

    <el-dialog
      top="30px"
      width="600px"
      class="dialog-sm"
      title="提示"
      append-to-body
      :close-on-click-modal="false"
      :before-close="rejectBeforeClose"
      :visible.sync="rejectVisible"
    >
      <p>请输入拒绝理由</p>
      <el-input v-model="rejectDes" rows="5" placeholder="输入拒绝理由" type="textarea"></el-input>
      <div class="text-center mt-3">
        <el-button @click="handleReject" type="primary" :loading="submitLoading" class="btn-long">
          确定拒绝
        </el-button>
        <el-button @click="rejectBeforeClose" class="btn-long">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { printA4, nzhToMoney } from '@vimi/utils-tool'

import { enumContractType } from '@/credit/plugins/enumTown'

export default {
  components: {},
  props: {
    visible: Boolean,
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
    isRenewal: Boolean,
  },
  data() {
    return {
      enumContractType,
      initLoading: false,
      contract: {},
      notice: {},
      submitLoading: false,

      contractData: {},
      noticeData: {},

      // 拒绝
      rejectVisible: false,
      rejectDes: '',
    }
  },
  computed: {
    ...mapGetters(['user', 'org', 'entrustContract']),
    placeholderTime() {
      return `请输入${enumContractType[this.contract.contract_type] || '授信合同'}时间`
    },
    placeholderNo() {
      return `请输入${enumContractType[this.contract.contract_type] || '授信合同'}号`
    },
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    relatedId() {
      return this.relatedData && this.relatedData.customer_related_id
    },
    isViewModel() {
      return this.viewMode || +this.relatedData.loan_notice_status > 1
    },
    hasContract() {
      return this.contract.entrust_contract_id
    },
    // 银行是否认领
    hasBank() {
      return !!this.relatedData.bank_id
    },
    // 电子保函状态
    projectEleStatus() {
      return +this.relatedData.ele_letter_status || 0
    },
    // 电子保函是否已回执
    hasEleReceipt() {
      return +this.projectEleStatus === 2
    },
    hasNotice() {
      return this.notice.loan_notice_id && this.hasBank
    },
    noticeNo() {
      return this.hasNotice
        ? `${this.contract.gua_org_name_short || ''}放款通字[${
            this.notice.notice_word_no || ''
          }]第${this.notice.notice_number_no || ''}号`
        : 'XXXX放款通字[XXXX]第XX号'
    },
    loanFundsChinese() {
      const funds = Number.parseFloat(this.contract.reply_funds)
      return isNaN(funds) ? '' : nzhToMoney(funds * 1e4)
    },
    loanMonths() {
      const years = Number.parseFloat(this.contract.load_years)
      return isNaN(years) ? '0' : years * 12
    },
    noticeDate() {
      return this.$utils.dateFormat(this.notice.notice_date, 'yyyy年MM月dd日') || '年 月 日'
    },
    printId() {
      return `print-wrap-${this.notice.loan_notice_id}`
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
      },
      deep: true,
      immediate: true,
    },
    entrustContract: {
      handler: function () {
        this.initContractByExist()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },

    async getData() {
      this.initLoading = true
      this.$store.dispatch('getEntrustContract', this.relatedId)
      await this.getNotice()
      this.initLoading = false
    },

    initContractByExist() {
      this.contract = { ...this.entrustContract }
      if (!this.contract.bank_name) {
        this.contract.bank_name = this.relatedData.bank_name || ''
      }
    },

    async getNotice() {
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'loan_notice', {
          'customer_related_id.eq': this.relatedId,
        })
      )
      if (res && res.data && res.data.length) {
        this.notice = res.data[0]
      }
    },

    submit(isReject = 0) {
      if (this.isBankOrg) {
        if (!this.validateBank(isReject)) return
      } else if (!this.validateContract()) {
        return
      }

      const contractKeys = [
        'bank_name',
        'contract_date',
        'credit_contract_no',
        'gua_contract_date',
        'ensure_contract_no',
        'reply_funds',
      ]
      this.contractData = {}
      for (const key of contractKeys) {
        this.contractData[key] = this.contract[key]
      }

      const noticeKeys = [
        // 'gua_company_sign', // 取当前担保企业法人
        'notice_date',
        'bank_agent_name',
        'notice_date_sign',
      ]
      this.noticeData = {}
      for (const key of noticeKeys) {
        this.noticeData[key] = this.notice[key]
      }

      if (this.isBankOrg) {
        this.noticeData.is_receipted = isReject ? 2 : 1

        if (isReject) {
          this.rejectVisible = true
        } else {
          this.apiData()
        }
      } else {
        this.apiData()
      }
    },

    validateContract() {
      const enumValid = {
        contract_date: this.placeholderTime,
        credit_contract_no: this.placeholderNo,
        gua_contract_date: '请填写保证合同时间',
        ensure_contract_no: '请填写保证合同编号',
        reply_funds: '请填写放款金额',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    validateBank(isReject) {
      if (isReject) {
        return
      }
      const enumValid = {
        notice_date: '请选择放款通知时间',
        bank_agent_name: '请填写银行经办人',
        notice_date_sign: '请填写签收日期',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.notice[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    apiData() {
      this.submitLoading = true
      Promise.all([
        this.putContract(this.contract.entrust_contract_id, this.contractData),
        this.hasNotice
          ? this.putData(this.notice.loan_notice_id, this.noticeData)
          : this.postData({
              ...this.noticeData,
              // 是否是续贷
              is_extended_loan: this.isRenewal ? 1 : 0,
            }),
      ])
        .then(() => {
          this.$message.success('提交成功')
          this.getData()
          this.rejectBeforeClose()
          this.$emit('success', 0)
        })
        .catch(() => {
          this.$message.error('提交失败')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },

    putData(id, data) {
      return this.$utils.promise(this.$api.updateData(this.$serviceName, 'loan_notice', id, data))
    },

    postData(data) {
      data.customer_related_id = this.relatedId
      return this.$utils.promise(this.$api.addData(this.$serviceName, 'loan_notice', data))
    },

    async putContract(id, data) {
      return this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'entrust_contract', id, data)
      )
    },

    handleReject() {
      this.noticeData.confuse_des = this.rejectDes
      this.noticeData.notice_date_sign = this.$utils.dateFormat(new Date())
      this.noticeDate.bank_agent_name = this.user.realName
      this.apiData()
    },

    rejectBeforeClose() {
      this.rejectDes = ''
      this.rejectVisible = false
    },

    printPage() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        body {font-family: SimSun;}
        .text-indent{text-indent: 2rem;}
        .text-decoration{text-decoration: underline;}
        .page-content {max-width: 794px;margin: 0 auto;font-size: 1.2rem;line-height: 2;}
        .notice-divider {height: 2px;border: 1px dashed #333;margin-top: 3rem;margin-bottom: 3rem;}
      `
      )
    },
  },
  directives: {
    anchor: {
      bind(el, { value }, vnode) {
        el.onclick = () => {
          if (!value) return
          const ref = vnode.context.$refs[value]
          if (ref && ref.focus) {
            ref.focus()
          }
        }
      },
    },
  },
}
</script>
<style lang="scss" scoped>
.pre-style {
  border: 1px solid $border-color;
  padding: 2rem;
  background-color: #fefefe;
}
.page-content {
  max-width: 794px;
  margin: 0 auto;
  font-size: 1.2rem;
  line-height: 2;
}
.text-indent {
  text-indent: 2.4rem;
}
.text-decoration {
  text-decoration: underline;
}
.notice-divider {
  height: 2px;
  border: 1px dashed #333;
  margin-top: 3rem;
  margin-bottom: 3rem;
}
.input-td /deep/ .el-input-group__append {
  background-color: #ffe;
  border: none;
}
</style>
